//
//  LanBDepositWebController.m
//  LanBKit_Example
//
//  Created by v on 2020/11/3.
//  Copyright © 2020 v. All rights reserved.
//

#import "LanBDepositWebController.h"
#import <WebKit/WebKit.h>
#import <Masonry/Masonry.h>
#import <ReactiveObjC/ReactiveObjC.h>
#import <MJExtension/MJExtension.h>
#import <NSString+Extend.h>
#import "LanBDepositer.h"

@interface LanBDepositWebController () <WKUIDelegate, WKNavigationDelegate>
@property (nonatomic, strong) WKWebView*    wkWebView;
@property (nonatomic, strong) NSString*     urlStr;
@property (nonatomic, strong) NSString*     htmlStr;
@end

@implementation LanBDepositWebController

- (instancetype)initWithUrlString:(NSString *)urlString
{
    if (self = [super initWithNibName:nil bundle:nil]) {
        _urlStr = urlString;
    }
    return self;
}

- (instancetype)initWithHtmlString:(NSString *)htmlString
{
    if (self = [super initWithNibName:nil bundle:nil]) {
        _htmlStr = htmlString;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self _loadData];
}

- (void)reload
{
    [self _loadData];
}

#pragma mark - private
- (void)_loadData
{
    if (self.htmlStr.length > 0) {
        [self.wkWebView loadHTMLString:self.htmlStr baseURL:nil];
    }
    
    if (self.urlStr.length > 0) {
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.urlStr]];
        [self.wkWebView loadRequest:request];
    }
    
}

#pragma mark - WkUIDelegate
-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(nonnull WKWebViewConfiguration *)configuration forNavigationAction:(nonnull WKNavigationAction *)navigationAction windowFeatures:(nonnull WKWindowFeatures *)windowFeatures
{
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
        return webView;
    }
    return [[WKWebView alloc]init];;
}

#pragma mark - WKNavigationDelegate
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURLRequest *request  = navigationAction.request;
    NSString     *scheme   = request.URL.scheme;
    // url decode
    NSString     *urlAbStr = navigationAction.request.URL.absoluteString.stringByRemovingPercentEncoding;
    
    // wx原生 H5
    NSString *redirect_url = LanBDepositer.shared.wxH5Scheme?:@"";
    if (![redirect_url hasSuffix:@"://"]) {
        redirect_url = [redirect_url stringByAppendingString:@"://"];
    }
    if ([urlAbStr hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"] && ![urlAbStr hasSuffix:[NSString stringWithFormat:@"redirect_url=%@", redirect_url]]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        NSString *baseUrl = urlAbStr.lanB_baseUrl;
        NSMutableDictionary *param = urlAbStr.lanB_queryDictionary.mutableCopy;
        param[@"redirect_url"] = redirect_url;
        NSString *newUrl = [baseUrl lanB_queryWithDictionary:param];
        
        NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:newUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        newRequest.allHTTPHeaderFields = request.allHTTPHeaderFields;
        [newRequest setValue:redirect_url forHTTPHeaderField:@"Referer"]; // ext:https://blog.csdn.net/auccy/article/details/78328825
        [webView loadRequest:newRequest];
        return;
    }
    
    if ([redirect_url isEqualToString:urlAbStr]) { // 防止 wx h5 open redirect url scheme
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    // ali原生H5 , 替换 fromAppUrlScheme
    NSString *aliFromScheme = LanBDepositer.shared.aliScheme?:@"";
    if ([@"alipay" isEqualToString:scheme] && [UIApplication.sharedApplication canOpenURL:request.URL]) {
        NSString *baseUrl = urlAbStr.lanB_baseUrl;
        NSString *query   = urlAbStr.lanB_query;
        // 1.直接替换
//        query = [query stringByReplacingOccurrencesOfString:@"alipays" withString:aliFromScheme];
//        NSString *link = [NSString stringWithFormat:@"%@?%@", baseUrl, query];
//        link = [link stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet];
//
//        decisionHandler(WKNavigationActionPolicyCancel);
//        if (@available(iOS 10.0, *)) {
//            [UIApplication.sharedApplication openURL:[NSURL URLWithString:link] options:@{} completionHandler:NULL];
//        } else {
//            [UIApplication.sharedApplication openURL:[NSURL URLWithString:link]];
//        }
//        return;
        
        // 2.转Dictionary修改
        NSMutableDictionary *paramDic = [[query mj_JSONObject] mutableCopy];
        if ([paramDic isKindOfClass:NSDictionary.class]) {
            paramDic[@"fromAppUrlScheme"] = aliFromScheme;
            NSString *link = [NSString stringWithFormat:@"%@?%@", baseUrl, paramDic.mj_JSONString];
            link = [link stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet];
            NSURL *urlLink = [NSURL URLWithString:link];
            decisionHandler(WKNavigationActionPolicyCancel);
            if (@available(iOS 10.0, *)) {
                [UIApplication.sharedApplication openURL:urlLink options:@{} completionHandler:^(BOOL success) {
                    if (LanBDepositer.shared.openUrlBlock) {
                        LanBDepositer.shared.openUrlBlock(success, urlLink);
                    }
                }];
            } else {
                BOOL success = [UIApplication.sharedApplication openURL:urlLink];
                if (LanBDepositer.shared.openUrlBlock) {
                    LanBDepositer.shared.openUrlBlock(success, urlLink);
                }
            }
            return;
        }
    }
    
    if ([@"http" isEqualToString:scheme] || [@"https" isEqualToString:scheme]) {
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    
    if ([UIApplication.sharedApplication canOpenURL:request.URL]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        if (@available(iOS 10.0, *)) {
            [UIApplication.sharedApplication openURL:request.URL options:@{} completionHandler:^(BOOL success) {
                if (LanBDepositer.shared.openUrlBlock) {
                    LanBDepositer.shared.openUrlBlock(success, request.URL);
                }
            }];
        } else {
            BOOL success = [UIApplication.sharedApplication openURL:request.URL];
            if (LanBDepositer.shared.openUrlBlock) {
                LanBDepositer.shared.openUrlBlock(success, request.URL);
            }
        }
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}


#pragma mark - set get
-(WKWebView *)wkWebView
{
    if (!_wkWebView) {
        /*
         //创建网页配置对象
         WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
         
         // 创建设置对象
         WKPreferences *preference = [[WKPreferences alloc]init];
         //最小字体大小 当将javaScriptEnabled属性设置为NO时，可以看到明显的效果
         preference.minimumFontSize = 0;
         //设置是否支持javaScript 默认是支持的
         preference.javaScriptEnabled = YES;
         // 在iOS上默认为NO，表示是否允许不经过用户交互由javaScript自动打开窗口
         preference.javaScriptCanOpenWindowsAutomatically = YES;
         config.preferences = preference;
         
         config.userContentController = [[WKUserContentController alloc]init];
         // 是使用h5的视频播放器在线播放, 还是使用原生播放器全屏播放
         config.allowsInlineMediaPlayback = YES;
         //设置视频是否需要用户手动播放  设置为NO则会允许自动播放
         config.requiresUserActionForMediaPlayback = YES;
         //设置是否允许画中画技术 在特定设备上有效
         config.allowsPictureInPictureMediaPlayback = YES;
         //设置请求的User-Agent信息中应用程序名称 iOS9后可用
         config.applicationNameForUserAgent = @"ChinaDailyForiPad";
         WKWebView *web = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
         */
        
        WKWebView *web = [[WKWebView alloc] init];
        web.backgroundColor = UIColor.whiteColor;
        [self.view addSubview:web];
        @weakify(self)
        [web mas_updateConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.left.right.top.bottom.equalTo(self.view);
        }];
        
        web.UIDelegate = self;
        web.navigationDelegate = self;
        web.allowsBackForwardNavigationGestures = YES;
        
        _wkWebView = web;
    }
    return _wkWebView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
